<template>
  <div class="con table-gl-w">
    <div class="search-con search-w">
      <FilterTable :filterItem="filterItem" :isReset="true" @search="searchByVal" />
    </div>
    <div class="table-gl-con">
      <TableWrap style="flex: 1" @refresh="getList">
        <template #headerLeft>
          <a-button style="margin-right: 10px" class="gray-outline" @click="setInventoryPrice" v-if="$authPass('inventory.fba.inventory.updatePrice')">设置库存单价</a-button>
          <a-button style="margin-right: 10px" class="gray-outline" @click="showImportPairDialog = true" v-if="$authPass('inventory.fba.inventory.updatePrice')">批量导入库存单价</a-button>
          <a-button style="margin-right: 10px" class="gray-outline" @click="initinventory.visible = true" v-if="$authPass('inventory.fba.inventory.init')">库存初始化</a-button>
          <a-button style="margin-right: 10px" class="gray-outline" @click="updateUser" :loading="updateUserLoading" v-if="$authPass('inventory.fba.inventory.updateSeller')">更新商品所属销售员</a-button>
        </template>
        <template #headerRight>
          <a-popover content="导出库存" style="font-size: 16px">
            <a-button type="text" @click="refresh">
              <template #icon>
                <icon-download />
              </template>
            </a-button>
          </a-popover>
        </template>
        <template #tableBody>
          <a-table ref="table" size="mini" class="table-singe-line" :bordered="{ cell: true }" v-model:selectedKeys="rowSelectList" @selection-change="selectColumn" @sorter-change="sortChange" row-key="id" :loading="loading" :summary="summary" :row-selection="rowSelection" :columns="columns" :data="tableList" :pagination="false" :scroll="{ x: '100%', y: '100%' }">
            <template #columns>
              <a-table-column title="序号" :width="60">
                <template #cell="{ record, rowIndex }">
                  {{ rowIndex + 1 }}
                </template>
              </a-table-column>
              <a-table-column title="店铺" :width="140">
                <template #cell="{ record, rowIndex }">
                  {{ record.shopName }}
                </template>
              </a-table-column>
              <a-table-column title="销售员" :width="60">
                <template #cell="{ record, rowIndex }">
                  {{ record.salesmanName }}
                </template>
              </a-table-column>
              <a-table-column title="FNSKU" :width="100">
                <template #cell="{ record, rowIndex }">
                  <a-popover>
                    <p style="width: 100%" class="text-limit">{{ record.fnsku }}</p>
                    <template #content>
                      <p>{{ record.fnsku }}</p>
                    </template>
                  </a-popover>
                </template>
              </a-table-column>
              <a-table-column title="msku" :width="100">
                <template #cell="{ record, rowIndex }">
                  <a-popover>
                    <p style="width: 100%" class="text-limit">{{ record.msku }}</p>
                    <template #content>
                      <p>{{ record.msku }}</p>
                    </template>
                  </a-popover>
                </template>
              </a-table-column>
              <a-table-column title="图片" :width="60">
                <template #cell="{ record, rowIndex }">
                  <ImgPopover :src="record.productImg">
                    <template #con>
                      <a-image width="40" height="40" fit="contain" :src="record.productImg" />
                    </template>
                  </ImgPopover>
                </template>
              </a-table-column>
              <a-table-column title="SKU" :width="100">
                <template #cell="{ record, rowIndex }">
                  <ShowSpuDetailBySku :val="record.sku" :showLimit="true" :rows="2" />
                </template>
              </a-table-column>
              <a-table-column title="类目" :width="80" data-index="cateName">
                <template #cell="{ record, rowIndex }">
                  <a-popover>
                    <p style="width: 100%" class="text-limit">{{ record.cateName }}</p>
                    <template #content>
                      <p>{{ record.cateName }}</p>
                    </template>
                  </a-popover>
                </template>
              </a-table-column>

              <a-table-column :width="260">
                <template #title>
                  <a-popover content="FBA在途数量按货件已标记发货，未接收数量计算">
                    <p>
                      <span>FBA在途仓</span>
                      <icon-question-circle />
                    </p>
                  </a-popover>
                </template>
                <a-table-column title="可用库存" :width="100" data-index="amtOnWay" :sortable="{ sortDirections: ['ascend', 'descend'] }">
                  <template #cell="{ record, rowIndex }">
                    {{ record.amtOnWay }}
                  </template>
                </a-table-column>
                <a-table-column title="平均单价" :width="70" data-index="purchaseInAmt">
                  <template #cell="{ record, rowIndex }">
                    {{ record.amtOnWay }}
                  </template>
                </a-table-column>
                <a-table-column title="货值" :width="70" data-index="valueOnWay" :sortable="{ sortDirections: ['ascend', 'descend'] }">
                  <template #cell="{ record, rowIndex }">
                    {{ record.valueOnWay }}
                  </template>
                </a-table-column>
              </a-table-column>
              <a-table-column :width="260">
                <template #title>
                  <a-popover content="根据FBA库存分类账明细报告汇总出FBA库存数据，该数据汇有48小时延迟">
                    <p>
                      <span>FBA映射仓</span>
                      <icon-question-circle />
                    </p>
                  </a-popover>
                </template>
                <a-table-column title="可用库存" :width="100" data-index="amtMapped" :sortable="{ sortDirections: ['ascend', 'descend'] }">
                  <template #cell="{ record, rowIndex }">
                    {{ record.amtMapped }}
                  </template>
                </a-table-column>
                <a-table-column title="不良品" :width="80" data-index="amtDefectiveMapped" :sortable="{ sortDirections: ['ascend', 'descend'] }">
                  <template #cell="{ record, rowIndex }">
                    {{ record.amtDefectiveMapped }}
                  </template>
                </a-table-column>
                <a-table-column title="平均单价" :width="70" data-index="purchaseInAmt">
                  <template #cell="{ record, rowIndex }">
                    {{ record.priceMapped }}
                  </template>
                </a-table-column>
                <a-table-column title="货值" :width="70" data-index="valueMapped" :sortable="{ sortDirections: ['ascend', 'descend'] }">
                  <template #cell="{ record, rowIndex }">
                    {{ record.valueMapped }}
                  </template>
                </a-table-column>
              </a-table-column>
              <a-table-column title="总库存" :width="100" data-index="inventoryTotal" :sortable="{ sortDirections: ['ascend', 'descend'] }">
                <template #cell="{ record, rowIndex }">
                  {{ record.inventoryTotal }}
                </template>
              </a-table-column>
              <a-table-column title="总货值" :width="100" data-index="inventoryValue" :sortable="{ sortDirections: ['ascend', 'descend'] }">
                <template #cell="{ record, rowIndex }">
                  {{ record.inventoryValue }}
                </template>
              </a-table-column>
              <a-table-column :width="260">
                <template #title>
                  <a-popover content="FBA实时库存，获取FBA实时库存报告每隔1小时同步一次">
                    <p>
                      <span>FBA实时库存</span>
                      <icon-question-circle />
                    </p>
                  </a-popover>
                </template>
                <a-table-column title="可用库存" :width="100" data-index="amtAvailableCurrent" :sortable="{ sortDirections: ['ascend', 'descend'] }">
                  <template #cell="{ record, rowIndex }">
                    {{ record.amtAvailableCurrent }}
                  </template>
                </a-table-column>
                <a-table-column title="不良品库存" :width="100" data-index="amtDefectiveCurrent" :sortable="{ sortDirections: ['ascend', 'descend'] }">
                  <template #cell="{ record, rowIndex }">
                    {{ record.amtDefectiveCurrent }}
                  </template>
                </a-table-column>
              </a-table-column>
              <a-table-column title="操作" :width="60" fixed="right">
                <template #cell="{ record, rowIndex }">
                  <a-button type="text" size="mini" @click="show(record)">详情</a-button>
                </template>
              </a-table-column>
            </template>
            <template #summary-cell="{ column, record, rowIndex }">
              <div>{{ record[column.dataIndex] }}</div>
            </template>
          </a-table>
        </template>
      </TableWrap>
      <div class="pagination-footer">
        <a-pagination size="mini" :page-size-options="[20, 50, 100, 200, 500]" show-total show-page-size :total="pageNation.total" :default-page-size="pageNation.pageSize" :current="pageNation.pageNum" style="float: right" @page-size-change="sizeChange" @change="changePage" />
      </div>
    </div>
  </div>
  <ShowDetail ref="showDetail" :onWayInventoryId="onWayInventoryId" :mappedInventoryId="mappedInventoryId" />
  <SetPrice ref="setPrice" :list="rowSelectItems" @save="setPriceSuccess" />
  <ImportPrice v-if="showImportPairDialog" :isShow="showImportPairDialog" @closed="showImportPairDialog = false" @success="sizeChange(20)" />
  <InitInventory ref="initinventory" @save="setPriceSuccess" />
</template>

<script lang="ts">
  import { defineComponent, ref, reactive, toRefs } from 'vue'
  import TableWrap from '@/components/TableWrap.vue'
  import FilterTable from '@/components/TableFilter.vue'
  import { findWarehouseListByParam, findShopListByShare } from '@/api/warehouse'
  import { findFbaInventoryPage, updateFbaInventoryOperator, sumFbaInventoryParam } from '@/api/inventory'
  import { getCategoryList } from '@/api/product'
  import { getOrganizesUser } from '@/api/system'
  import ShowDetail from './components/fbaInventoryDetail.vue'
  import SetPrice from './components/setPrice.vue'
  import ImportPrice from './components/importPrice.vue'
  import InitInventory from './components/initInventory.vue'
  import _ from 'lodash-es'
  import { Message } from '@arco-design/web-vue'
  import { Notification, Button } from '@arco-design/web-vue'
  import { IconCloseCircle } from '@arco-design/web-vue/es/icon'
  import dayjs from 'dayjs'
  export default defineComponent({
    components: { TableWrap, FilterTable, ShowDetail, SetPrice, ImportPrice, InitInventory },
    setup() {
      const showDetail = ref()
      const setPrice = ref()
      const table = ref()
      const initinventory = ref()
      const data: any = reactive({
        loading: false,
        tableList: [],
        filterItem: [
          {
            key: 'shopIds',
            placeholder: '选择店铺',
            label: '店铺',
            value: ref(),
            type: 'select_multiple',
            width: 180,
            optionItems: [],
            attrs: {
              multiple: true,
              'max-tag-count': 1,
            },
          },
          {
            key: 'salesmanId',
            label: '运营',
            placeholder: '选择运营',
            value: ref(),
            type: 'select',
            width: 180,
            optionItems: [],
            attrs: {
              'allow-search': true,
            },
          },
          {
            type: 'input_keyword',
            key: 'skus',
            keyItems: [
              { label: 'SKU', value: 'skus' },
              { label: 'MSKU', value: 'mskus' },
              { label: 'FNSKU', value: 'fnskus' },
            ],
            keyWidth: '90',
            value: ref(),
            placeholder: '请输入',
            label: 'SKU',
            width: 180,
            isMultiple: true,
          },
          {
            type: 'cascader',
            key: 'cateId',
            optionItems: [],
            keyWidth: '120',
            value: ref(),
            placeholder: '请选择',
            label: '类目',
            width: 200,
            isMultiple: false,
          },
          {
            key: 'mappedStock',
            label: '映射仓库存',
            value: ref(),
            type: 'select',
            width: 120,
            optionItems: [
              { label: '全部', value: '' },
              { label: '可用数>0', value: '1' },
              { label: '可用数=0', value: '0' },
              { label: '不良品数>0', value: '2' },
              { label: '不良品数=0', value: '3' },
              // { label: '不良品数>0', value: '3' },
              // { label: '不良品数=0', value: '4' },
            ],
          },
          {
            key: 'onWayStock',
            label: '在途仓库存',
            value: ref(),
            type: 'select',
            width: 120,
            optionItems: [
              { label: '全部', value: '' },
              { label: '可用数>0', value: '1' },
              { label: '可用数=0', value: '0' },
            ],
          },
          {
            key: 'priceType',
            label: '在途仓单价',
            value: ref('priceOnWay'),
            type: 'price_sel',
            width: 115,
            optionItems: [
              { label: '在途仓单价', value: 'priceOnWay' },
              { label: '映射仓单价', value: 'priceMapped' },
            ],
            optionField: {
              //最小值和最大值的转换
              min: 'priceMin',
              max: 'priceMax',
            },
          },
        ],
        pageNation: { total: 0, pageSize: 20, pageNum: 1 },
        rowSelection: {
          type: 'checkbox',
          showCheckedAll: true,
        },
        rowSelectList: [],
        rowSelectItems: [],
        onWayInventoryId: '',
        mappedInventoryId: '',
        searchValue: {},
        showImportPairDialog: false,
        updateUserLoading: false,
        summartData: {},
      })
      const summary = () => {
        console.log(data.summartData, 'data.summartData')

        let obj = {
          amtOnWay: 0,
          valueOnWay: 0,
          amtMapped: 0,
          amtDefectiveMapped: 0,
          valueMapped: 0,
          inventoryTotal: 0,
          inventoryValue: 0,
        }

        obj.amtOnWay = data.summartData?.amtOnWay || 0
        obj.valueOnWay = data.summartData?.valueOnWay || 0
        obj.amtMapped = data.summartData?.amtMapped || 0
        obj.amtDefectiveMapped = data.summartData?.amtDefectiveMapped || 0
        obj.valueMapped = data.summartData?.valueMapped || 0
        obj.inventoryTotal = data.summartData?.inventoryTotal || 0
        obj.inventoryValue = data.summartData?.inventoryValue || 0

        return [
          {
            cateName: '合计',
            ...obj,
          },
        ]
      }

      const searchByVal = (info: any) => {
        let obj = _.cloneDeep(info)
        data.searchValue = {}
        for (const key in obj) {
          if (key == 'date' && obj[key]) {
            data.searchValue.startDate = `${obj[key][0]} 00:00:00`
            data.searchValue.endDate = `${obj[key][1]} 23:59:59`
          } else {
            data.searchValue[key] = obj[key]
          }
        }
        data.pageNation.pageNum = 1
        getList()
        getSummartData()
      }

      const changePage = (val: number) => {
        data.pageNation.pageNum = val
        getList()
      }

      const sizeChange = (val: number) => {
        data.pageNation.pageNum = 1
        data.pageNation.pageSize = val
        getList()
      }

      const sortChange = (item: any, extra: any) => {
        if (extra) {
          data.searchValue.sortField = item
          data.searchValue.sortType = extra == 'ascend' ? '1' : '-1'
        } else {
          data.searchValue.sortField = ''
          data.searchValue.sortType = ''
        }
        getList()
      }

      const selectColumn = (val: any) => {
        data.rowSelectList = val
        data.rowSelectItems = []
        val.forEach((e: any) => {
          let obj = data.tableList.find((el: any) => e == el.id)
          data.rowSelectItems.push(obj)
        })
      }

      const getList = async (searchValue?: any) => {
        let params = {
          ...data.searchValue,
          pageNum: data.pageNation.pageNum,
          pageSize: data.pageNation.pageSize,
        }
        data.loading = true
        const res: any = await findFbaInventoryPage(params)
        if (res.code == 'SUCCESS') {
          if (!res.data) {
            Notification.clear()
            Notification.info({
              title: '提示',
              content: '请先进行库存初始化操作!',
              duration: 5000,
              closable: true,
            })
          } else {
            data.tableList = res.data.records
            data.pageNation.total = res.data.total
          }
        }

        data.loading = false
      }

      const getShopListByShare = async () => {
        const res = await findShopListByShare({ share: false })
        let arr = res?.data
        arr.map((e: any) => {
          e.label = e.shopName
          e.value = e.shopId
        })
        data.filterItem[0].optionItems = arr
      }

      const getCategory = async () => {
        const res: any = await getCategoryList()
        data.filterItem[3].optionItems = res.data
      }
      const show = (info: any) => {
        data.onWayInventoryId = info.onWayInventoryId
        data.mappedInventoryId = info.mappedInventoryId
        showDetail.value.visible = true
      }

      // 获取用户列表
      const getUSerList = async () => {
        let params = {
          depart: false,
          pageNum: 1,
          pageSize: 1000,
        }
        const res: any = await getOrganizesUser(params)
        if (res.code == 'SUCCESS') {
          let userList = res?.data?.records
          userList.map((e: any) => {
            e.label = e.userName
            e.value = e.id
            return e
          })
          data.filterItem[1].optionItems = userList
        }
      }

      const setInventoryPrice = () => {
        if (data.rowSelectList.length <= 0) {
          return Message.error('请先选择需要操作的数据')
        }
        setPrice.value.visible = true
      }

      const updateUser = async () => {
        if (data.rowSelectList.length <= 0) {
          return Message.error('请先选择需要操作的数据')
        }
        data.updateUserLoading = true
        try {
          const res: any = await updateFbaInventoryOperator({ ids: data.rowSelectList })
          if (res.code == 'SUCCESS') {
            data.rowSelectList.forEach((e: any) => {
              table.value.select(e, false)
            })
          }
          data.updateUserLoading = false
        } catch (error) {
          data.updateUserLoading = false
        }
      }

      const setPriceSuccess = () => {
        data.rowSelectList.forEach((e: any) => {
          table.value.select(e, false)
        })
      }

      const getSummartData = async () => {
        let params = {
          ...data.searchValue,
        }
        const res = await sumFbaInventoryParam(params)
        data.summartData = res.data || {}
      }

      getSummartData()
      getUSerList()
      getShopListByShare()
      getCategory()
      getList()
      return {
        ...(toRefs(data) as any),
        searchByVal,
        changePage,
        sizeChange,
        selectColumn,
        summary,
        sortChange,
        showDetail,
        show,
        getList,
        setPrice,
        setInventoryPrice,
        setPriceSuccess,
        table,
        initinventory,
        updateUser,
      }
    },
  })
</script>

<style lang="less" scoped>
  .icon-r {
    .arco-icon {
      font-size: 16px;
      color: #000430;
    }
  }
</style>
